package com.dxl.web.account.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.dxl.bean.session.Session;
import com.dxl.common.consts.SysConsts;
import com.dxl.common.spring.AppCtxHolder;
import com.dxl.common.utils.Utils;
import com.dxl.dao.common.context.SessionContext;
import com.dxl.service.account.AccountService;
import com.dxl.service.sysprop.SysPropCacheManager;
import com.dxl.web.common.utils.RequestUtils;

public class LoginInterceptor extends HandlerInterceptorAdapter {
	private Logger LOG = Logger.getLogger(LoginInterceptor.class);
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String sessionId = RequestUtils.getValueFromRequest(request, SysPropCacheManager.getPropValue(SysConsts.LOGINED_SESSION_ID_KEY));
		if (Utils.isBlank(sessionId)) {
			LOG.warn("没有登录，重定向到登录页面");
			response.sendRedirect(RequestUtils.getRoot(request) + "/login.jsp");
			return false;
		} 
		Session session = AppCtxHolder.getBean(AccountService.class).login(sessionId, null, null);
		if (Utils.isNull(session)) {
			LOG.warn("没有登录，重定向到登录页面");
			response.sendRedirect(RequestUtils.getRoot(request) + "/login.jsp");
			return false;
		}
		session.setIp(request.getRemoteHost());
		SessionContext.setSession(session);
		return true;
	}
}
